<!--  -->
<template>
  <div class="sale-container">
    <chart-title
      title="产品营销统计"
      @click="handleMore"
    />
    <el-empty
      v-if="proLineDataNull"
      description="暂无数据"
    />
    <template v-else>
      <div
        v-loading="proLineLoading&&proLoading"
        class="chart-container"
        style="width:100%;height:100%;min-height:200px;padding:20px 20px 0px;box-sizing:border-box;"
      >
        <div class="filter-container">
          <date-select
            ref="dateSelectRef"
            @dateChange="dateChange"
          />
        </div>
        <div
          class="chart-container"
          style="height:100%;display:flex;align-items:center;"
        >
          <div
            id="proLineSaleChart"
            style="width:50%;height:100%;min-height:200px;display:flex;align-items:center;"
          />
          <div
            id="proSaleChart"
            style="width:50%;height:100%;min-height:200px;display:flex;align-items:center;"
          />
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import {inject, onMounted, reactive, ref, toRefs, watch} from 'vue'
import {useRouter} from 'vue-router'

// echarts
import * as echarts from 'echarts'
import ChartTitle from './chartTitle.vue'
import DateSelect from './dateSelect.vue'
import {gradientColor} from '@/utils/commonFun.js'

export default {
  components: {
    ChartTitle,
    DateSelect,
  },
  setup(props, context) {
    const router = useRouter()
    const api = inject('api')
    var dateSelectRef = ref(null)
    var selectData = reactive({
      selectItem: null,
    })
    var reactiveData = reactive({
      proLineDataNull: false,
      proLineLoading: true,
      proLoading: true,
      proLineOption: {
        legend: {
          orient: 'vertical',
          bottom: 20,
          show: false,
        },
        tooltip: {
          trigger: 'item',
          triggerOn: 'click',
          showContent: true,
          formatter: function(e, t, n) {
            const data = e.data
            selectData.selectItem = { ...e.data, color: e.color }
            console.log(data, e, t, n, selectData.selectItem)

            const context = `
               <div>
                   <p class="tooltip_style"><span class="tooltip_left">总营销额：</span><span class="tooltip_right">${data.value}</span></p>
               </div>
            `
            return context
          },
        },
        color: [
          '#417ff9',
          '#ff9623',
          '#53c89c',
          '#fe9ec6',
          '#7666f9',
          '#7666f9',
          '#f9d25d',
        ],
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '80%',
            selectedMode: 'single',
            label: {
              position: 'inner',
              fontSize: 12,
              rotate: true,
              fontStyle: 'normal',
              fontWeight: 'normal',
            },
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      },
      proOption: {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c}',
        },
        color: ['#0d77a1', '#1f8cb7', '#2f98c1', '#48acd3', '#73c0de'],
        series: [
          {
            name: '产品营销额',
            type: 'funnel',
            left: '10%',
            top: 50,
            bottom: 40,
            width: '30%',
            min: 0,
            max: 100,
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending',
            gap: 2,
            label: {
              show: true,
              position: 'outsideFill',
              color: '#333',
            },
            labelLine: {
              length: 10,
              lineStyle: {
                width: 1,
                type: 'solid',
              },
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 1,
            },
            emphasis: {
              label: {
                fontSize: 20,
              },
            },
            data: [],
          },
        ],
      },
      proLineFilterData: {
        statisticsType: '2',
        startTime: null,
        endTime: null,
        productSelectType: '1',
      },
      proFilterData: {
        statisticsType: '2',
        startTime: null,
        endTime: null,
        productSelectType: '2',
        productLineId: 1,
      },
    })
    const handleMore = () => {
      var type = dateSelectRef.value?.dateType() || '1'
      router.push({
        path: '/statistics/sale',
        query: {
          tab: 'productView',
          type: type,
        },
      })
    }
    const dateChange = (val, bool) => {
      reactiveData.proLineFilterData.startTime = val[0]
      reactiveData.proLineFilterData.endTime = val[1]
      reactiveData.proFilterData.startTime = val[0]
      reactiveData.proFilterData.endTime = val[1]
      if (bool) {
        proLineChartInit()
        proChartInit()
      }
    }
    const proLineChartInit = async() => {
      var chartDom = document.getElementById('proLineSaleChart')
      chartDom.removeAttribute('_echarts_instance_')
      var myChart = echarts.init(chartDom)
      var res = await api.dashboard.GET_STATISCS_DATA(
        reactiveData.proLineFilterData
      )
      if (res.code === 0) {
        reactiveData.proLineLoading = false
        console.log(res.data)
        var list = res.data || []
        var dataLis = []
        for (var i = 0; i < list.length; i++) {
          dataLis.push({
            productLineId: list[i].productLineId,
            name: list[i].productLineName,
            value: list[i].returnAmount,
            color: reactiveData.proLineOption.color[i],
          })
        }
        reactiveData.proFilterData.productLineId =
          dataLis[0]?.productLineId || 0
        selectData.selectItem = dataLis[0] || null
        if (dataLis[0]) {
          dataLis[0].selected = true
        }
        reactiveData.proLineOption.series[0].data = dataLis
      } else {
        reactiveData.proLineLoading = false
      }
      if (!reactiveData.proLineOption.series[0].data?.length) {
        reactiveData.proLineDataNull = true
      }
      // 绘制图表
      myChart.setOption(reactiveData.proLineOption)
      window.onresize = function() {
        // 自适应大小
        myChart.resize()
      }
    }
    const proChartInit = async() => {
      var chartDom = document.getElementById('proSaleChart')
      chartDom.removeAttribute('_echarts_instance_')
      var myChart = echarts.init(chartDom)
      console.log(gradientColor('#417ff9', '#ff0000', 10))
      reactiveData.proOption.color = gradientColor(
        selectData.selectItem?.color,
        '#ff0000',
        10
      )
      var res = await api.dashboard.GET_STATISCS_DATA(
        reactiveData.proFilterData
      )
      if (res.code === 0) {
        reactiveData.proLoading = false
        console.log(res.data)
        var list = res.data || []
        var dataLis = []
        list.forEach((itm) => {
          dataLis.push({
            name: itm.productName,
            value: itm.returnAmount,
          })
        })
        reactiveData.proOption.series[0].data = dataLis
      } else {
        reactiveData.proLoading = false
      }
      // 绘制图表
      myChart.setOption(reactiveData.proOption)
      window.onresize = function() {
        // 自适应大小
        myChart.resize()
      }
    }
    watch(
      () => selectData.selectItem,
      (newval, oldval) => {
        console.log(newval)
        reactiveData.proFilterData.productLineId = newval?.productLineId
        proChartInit()
      },
      { deep: true }
    )
    onMounted(() => {
      proLineChartInit()
      proChartInit()
    })
    return {
      dateSelectRef,
      ...toRefs(reactiveData),
      dateChange,
      handleMore,
    }
  },
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.sale-container {
  width: 100%;
  height: 100%;
  padding: 20px 0px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .chart-container {
    position: relative;
    .filter-container {
      position: absolute;
      right: 20px;
      top: -4px;
      z-index: 10;
    }
  }
}
</style>
